//
//  BannerSlidingView.m
//  Dianping
//
//  Created by 祝文博 on 15/3/10.
//  Copyright (c) 2015年 KevinLab. All rights reserved.
//

#import "BannerSlidingView.h"
#import "Banner.h"

NSString *BannerSlidingViewDidPressNotificationName = @"BannerSlidingView_DidPress_NotificationName";

@interface BannerSlidingView() <UIScrollViewDelegate>

@property (nonatomic, strong) NSArray *banners;

@property (nonatomic, strong) NSMutableArray *images;
@property (nonatomic, strong) UIScrollView *scrollView;

@property (nonatomic, strong) UIPageControl *pageControl;
@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, assign) NSInteger numberOfPages;

@property (nonatomic, strong) NSMutableArray *bannerButtons;

@property (nonatomic, strong) NSTimer *timer;

@end

@implementation BannerSlidingView

- (instancetype)initWithFrame:(CGRect)frame banners:(NSArray *)banners
{
    if (banners.count == 0) {
        NSLog(@"No banners passed in.");
        return nil;
    }
    
    self.banners = banners;
    
    if (self = [super initWithFrame:frame]) {
        self.images = [NSMutableArray array];
        
        for (Banner *banner in self.banners) {
            [self.images addObject:banner.image];
        }
        
        if (self.images.count == 0) {
            return nil;
        }
        self.numberOfPages = self.images.count;
        _currentPage = 0;
        
        self.scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
        self.scrollView.contentSize = CGSizeMake(3 * self.scrollView.bounds.size.width, self.scrollView.bounds.size.height);
        self.scrollView.delegate = self;
        self.scrollView.bounces = NO;
        self.scrollView.pagingEnabled = YES;
        self.scrollView.showsHorizontalScrollIndicator = NO;
        self.scrollView.showsVerticalScrollIndicator = NO;
        [self addSubview:self.scrollView];
    }
    
    self.bannerButtons = [NSMutableArray array];
    for (int i = 0; i < 3; i++) {
        CGRect frame = CGRectMake(i * self.scrollView.bounds.size.width, 0, self.scrollView.bounds.size.width, self.scrollView.bounds.size.height);
        UIButton *bannerButton = [[UIButton alloc] initWithFrame:frame];
        [bannerButton addTarget:self action:@selector(bannerPressed) forControlEvents:UIControlEventTouchUpInside];
        [self.bannerButtons addObject:bannerButton];
        [self.scrollView addSubview:bannerButton];
    }
    
    self.pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, 20)];
    self.pageControl.center = CGPointMake(self.bounds.size.width / 2.0, self.bounds.size.height - self.pageControl.bounds.size.height / 2.0);
    self.pageControl.numberOfPages = self.images.count;
    self.pageControl.currentPage = 0;
    self.pageControl.enabled = NO;
    
    self.pageControl.pageIndicatorTintColor = [UIColor colorWithHex:0x999999];
    self.pageControl.currentPageIndicatorTintColor = [UIColor colorWithHex:0xfcbb01];
    
    [self addSubview:self.pageControl];
    
    if (self.images.count == 1) {
        [self.images addObject:[self.images firstObject]];
        [self.images addObject:[self.images firstObject]];
    }
    [self layoutScrollView];
    
    if (self.banners.count > 1) {
        self.pageControl.hidden = NO;
        self.scrollView.scrollEnabled = YES;
        [self startAutomaticScroll];
    } else {
        self.pageControl.hidden = YES;
        self.scrollView.scrollEnabled = NO;
    }
    return self;
}

#pragma mark - Private

- (void)bannerPressed
{
    Banner *banner = self.banners[self.currentPage];
    [[NSNotificationCenter defaultCenter] postNotificationName:BannerSlidingViewDidPressNotificationName object:banner];
}

- (void)startAutomaticScroll
{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(scrollToNextPage) userInfo:nil repeats:YES];
    self.timer.fireDate = [NSDate dateWithTimeIntervalSinceNow:3.0];
}

- (void)scrollToNextPage
{
    if (self.timer.isValid) {
        [self.scrollView scrollRectToVisible:CGRectMake(self.scrollView.bounds.size.width * 2.0, 0, self.scrollView.bounds.size.width, self.scrollView.bounds.size.height) animated:YES];
    }
}

- (void)setCurrentPage:(NSInteger)currentPage
{
    if (currentPage < 0) {
        currentPage = 0;
    } else if (currentPage >= _numberOfPages) {
        currentPage = _numberOfPages - 1;
    }
    
    _currentPage = currentPage;
    [self layoutScrollView];
}

- (void)layoutScrollView
{
    NSArray *imagesToShow = [self imagesToShow];
    for (int i = 0; i < self.bannerButtons.count; i++) {
        [((UIButton *)self.bannerButtons[i]) setBackgroundImage:imagesToShow[i] forState:UIControlStateNormal];
    }
    
    // Show the middle imageView
    self.scrollView.contentOffset = CGPointMake(self.scrollView.bounds.size.width, 0);
}

- (NSArray *)imagesToShow
{
    if (_currentPage == 0) {
        return @[[self.images lastObject], [self.images firstObject], self.images[1]];
    } else if (self.currentPage == self.images.count - 1) {
        return @[self.images[_currentPage - 1], self.images[_currentPage], [self.images firstObject]];
    } else {
        return @[self.images[_currentPage - 1], self.images[_currentPage], self.images[_currentPage + 1]];
    }
    
    return nil;
}

- (NSInteger)prevPage:(NSInteger)currentPage
{
    NSInteger prevPage = currentPage - 1;
    if (prevPage < 0) {
        prevPage = self.numberOfPages - 1;
    }
    
    return prevPage;
}

- (NSInteger)nextPage:(NSInteger)currentPage
{
    NSInteger nextPage = currentPage + 1;
    if (nextPage > self.numberOfPages - 1) {
        nextPage = 0;
    }
    
    return nextPage;
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView.contentOffset.x >= 2 * scrollView.bounds.size.width) {   // Reach the right most page
        self.currentPage = [self nextPage:self.currentPage];
        self.pageControl.currentPage = self.currentPage;
        [self layoutScrollView];
    }
    else if (scrollView.contentOffset.x <= 0) {     // Reach the left most page
        self.currentPage = [self prevPage:self.currentPage];
        self.pageControl.currentPage = self.currentPage;
        [self layoutScrollView];
    }
}

@end
